package com.zenika.zentracker.hibernate.jdbc;

import org.hibernate.Interceptor;
import org.hibernate.cfg.Settings;
import org.hibernate.jdbc.Batcher;
import org.hibernate.jdbc.BatcherFactory;
import org.hibernate.jdbc.ConnectionManager;

/**
 * This class replaces the default Hibernate one.
 * 
 * Hibernate uses a BatchingBatcherFactory or a non BatchingBatcherFactory depending on the settings of the
 * jdbcBatchSize property.
 * 
 * This class will be configured via the hibernate property "hibernate.jdbc.factory_class"
 * 
 * Example: hibernate.jdbc.factory_class=com.zenika.zentracker.hibernate.jdbc.ZenTrackerBatchingFactory
 * 
 * The Settings from the SessionFactory is retrieved from the Interceptor to check if we are in a Batching or
 * NonBatching case.
 * 
 * @author Zenika
 */
public class ZenTrackerBatchingFactory implements BatcherFactory {

    /*
     * (non-Javadoc)
     * 
     * @see org.hibernate.jdbc.BatcherFactory#createBatcher(org.hibernate.jdbc.ConnectionManager,
     *      org.hibernate.Interceptor)
     */
    public Batcher createBatcher(ConnectionManager connectionManager, Interceptor interceptor) {

        Settings settings = connectionManager.getFactory().getSettings();

        if (settings.getJdbcBatchSize() == 0) {
            return (Batcher) new ZenTrackerNonBatchingBatcher(connectionManager, interceptor);
        } else {
            return (Batcher) new ZenTrackerBatchingBatcher(connectionManager, interceptor);
        }
    }
}
